import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/core/utils/wifi/wifi_name_monitor.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/// WiFi选择专用输入框
class WiFiSelectorField extends ConsumerWidget {
  final ValueChanged<String?>? onSelectedWifiChanged;
  final VoidCallback onTap;
  final Color backgroundColor;
  final double borderRadius;

  const WiFiSelectorField({
    super.key,
    this.onSelectedWifiChanged,
    required this.onTap,
    this.backgroundColor = const Color(0xFFF7F7F7),
    this.borderRadius = 8.0,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final wifiNameAsync = ref.watch(wifiNameProvider);
    wifiNameAsync.whenData((name) {
      if (onSelectedWifiChanged != null) {
        onSelectedWifiChanged!(name);
      }
    });
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 48.h,
        decoration: BoxDecoration(
          color: backgroundColor,
          borderRadius: BorderRadius.circular(borderRadius),
        ),
        child: Row(
          children: [
            // WiFi图标
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: Icon(Icons.wifi, color: Color(0xFF666666), size: 18),
            ),

            // WiFi名称
            Expanded(
              child: wifiNameAsync.when(
                data: (name) => Text(
                  name ?? '请选择WiFi',
                  style: TextStyle(
                    fontSize: context.textTheme.headlineMedium!.fontSize,
                    color: name == null
                        ? context.customColorThemeNonNull.gy4
                        : context.customColorThemeNonNull.textColor1,
                  ),
                ),
                loading: () => SizedBox.shrink(),
                error: (error, _) => Text(
                  error is WifiPermissionException
                      ? '无法获取WiFi，请在系统设置中开启定位权限'
                      : '无法获取WiFi名称',
                  style: TextStyle(
                    fontSize: context.textTheme.headlineMedium!.fontSize,
                    color: context.customColorThemeNonNull.gy4,
                  ),
                ),
              ),
            ),

            // 切换按钮
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12),
              child: Text(
                '切换WiFi',
                style: context.textTheme.bodyLarge!.copyWith(
                  color: context.colorScheme.primary,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
